package com.qinge.blog.security;

import com.qinge.blog.entity.BlogUser;
import com.qinge.blog.service.BlogUserRoleService;
import com.qinge.blog.service.BlogUserService;
import com.qinge.blog.utils.exception.ServiceException;
import com.qinge.blog.utils.result.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author QDW
 * @date 2022/4/29 11:24
 * @description UserDetailsServiceImpl
 **/
public class UserDetailsServiceImpl  implements UserDetailsService {
    @Autowired
    private BlogUserService userService;
    @Autowired
    private BlogUserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new ServiceException("用户不能为空");
        }

        // 根据用户名查询用户
        BlogUser user = userService.findUserByUsername(username);
        if (user == null) {
            throw new ServiceException(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        if (user != null) {
            // 获取该用户所拥有的权限
            List<String> roles = userRoleService.findRolesByUserId(user.getId());
            // 声明用户授权
            roles.forEach(role -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
                grantedAuthorities.add(grantedAuthority);
            });
        }

        user.setAuthorities(grantedAuthorities);
        return  user;
        // return new User(user.getUsername(), user.getPassword(), user.getEnabled(), user.getAccountNonExpired(), user.getCredentialsNonExpired(), user.getAccountNonLocked(), grantedAuthorities);
    }
}
